using Todos.Application.Roles.Specs;

namespace Todos.Application.Roles.Commands;

public class SyncRoleCommand : IRequest<ApiResult>, ICommand
{
    public required RoleInDto[] Dtos { get; set; }

    public bool IsSync { get; set; } = false;
}

public class SyncRoleCommandHandler(IServiceProvider provider) : IRequestHandler<SyncRoleCommand, ApiResult>
{
    public async Task<ApiResult> Handle(SyncRoleCommand request, CancellationToken cancellationToken)
    {
        var repository = provider.GetRepository<Role>();
        var logger = provider.GetLogger<SyncRoleCommandHandler>();

        if (request.IsSync)
        {
            var inRoleIds = request.Dtos.Where(m => m.Id > 0).Select(m => m.Id).ToArray();
            var delSpec = new RoleByIdsSpec(inRoleIds).Not();
            int delCount = await repository.DeleteBatchAsync(delSpec, cancellationToken);
            logger.LogInformation("同步角色，删除{delCount}条数据", delCount);
        }

        int createCount = 0, updateCount = 0;
        foreach (var dto in request.Dtos)
        {
            var (entity, isNew) = await repository.InsertOrUpdateAsync(dto, cancellationToken);
            if (isNew)
            {
                createCount++;
            }
            else
            {
                updateCount++;
            }
        }

        logger.LogInformation("同步角色，创建{createCount}条数据，更新{updateCount}条数据", createCount, updateCount);

        return new ApiResult(ApiResultType.Success);
    }
}

[MapTo(typeof(Role))]
public class RoleInDto : IDto
{
    public long Id { get; set; }
    public required string Name { get; set; }
    public bool IsLocked { get; set; }
}


